import { Applet } from "@/api/interface/iot";
import { getUserAppletList } from "@/api/modules/applet/userApplet";
import {
	delDictType,
	exportDictData,
	exportDictType,
	getDictTypeList,
	importDictData,
	importDictType
} from "@/api/modules/system/dict";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import UploadFile from "@/components/Upload/UploadFile.vue";
import { SYSTEM_ID } from "@/config/config";
import { useAuthButtonList } from "@/hooks/useAuthButtons";
import { getPageSize } from "@/hooks/useTable";
import { PublicStore } from "@/stores/modules/public";
import { bizDictType } from "@/utils/cacheUtil";
import { confirm, exportExcel, isSystem, showTips } from "@/utils/util";
import { ElMessage } from "element-plus";
import { getCurrentInstance, defineComponent, ComponentInternalInstance } from "vue";
import TypeDialog from "./components/typeDialog";
import DictDataList from "./dict-data-list";
export default defineComponent({
	emits: [],
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
		const proTableRef = ref();
		const state = reactive({
			systemId: SYSTEM_ID,
			appletList: [] as Applet.ResUserApplet[],
			searchParam: {} as any,
			searchColumns: [
				{ key: "dictName", label: proxy?.$t("dict.search_label.dictname") },
				{ key: "dictType", label: proxy?.$t("dict.search_label.dicttype") }
			]
		});
		const initParam = reactive({ systemId: state.systemId, dictName: "", pageSize: getPageSize({ offsetHeight: -76 }) });
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		const getTableList = async (params: any) => {
			return getDictTypeList({ ...params, ...initParam });
		};
		const btnList = ref<any>([]);
		const batchList = ref<any>([]);
		onMounted(async () => {
			let arr = await useAuthButtonList();
			// 获取页面按钮权限
			btnList.value = arr.filter((item: any) => item.type == "btn");
			batchList.value = arr.filter((item: any) => item.type == "batch");
			getAppletList();
		});
		const appName = ref("");
		const getAppletList = async () => {
			//默认是三三菜单管理
			// state.appletList = [{ id: SYSTEM_ID, key: SYSTEM_ID, name: "三三物联" }];
			if (state.systemId == "sansan") {
				let { result } = await getUserAppletList({ pageIndex: 1, pageSize: 99999, name: appName.value });
				state.appletList = result.records.filter((item: any) => item.type == "system" && isSystem(item.home));
				// state.appletList = state.appletList.concat(result.records || []);
			}
		};
		const loadList = () => {
			initParam.systemId = state.systemId;
			currentDictType.value = "";
			proTableRef.value.clearSelection();
			proTableRef.value.reset();
		};
		const currentItem = ref();
		const uploadFileEl = ref();
		const uploadFileDataEl = ref();
		const clickBtn = async (val: string, scope: any) => {
			switch (val) {
				case "add":
					detailDialog.visible = true;
					detailDialog.title = proxy?.$t("dict.dialog_title.add");
					currentItem.value = { status: 1, bizId: bizDictType.public, systemId: state.systemId };
					break;
				case "del":
					if (scope.selectList.length == 0) return ElMessage.error("至少选择一条数据操作");
					confirm({ content: "是否删除当前选择的记录？" }).then(async flag => {
						if (!flag) {
							return;
						}
						let { code, message } = await delDictType({ ids: scope.selectList.map((item: any) => item.id) });
						let ok = showTips(code, "删除字典类型", message);
						if (ok) {
							proTableRef.value.getTableList();
						}
					});
					break;
				case "mod":
					detailDialog.visible = true;
					detailDialog.title = proxy?.$t("dict.dialog_title.mod");
					currentItem.value = scope;
					break;
				case "import":
					uploadFileEl.value.selectingFile();
					break;
				case "importData":
					uploadFileDataEl.value.selectingFile();
					break;
				case "exportData":
					let { data, filename } = await exportDictData({}, getExportData(scope));
					exportExcel(data, filename);
					break;
				case "export":
					// if (scope.selectList.length == 0) return ElMessage.error("至少选择一条数据操作");
					let res = await exportDictType({}, getExportData(scope));
					exportExcel(res.data, res.filename);
					break;
			}
		};
		const getExportData = (scope: any) => {
			let str = "systemId=" + state.systemId + "&";
			if (scope.selectList.length != 0) {
				for (let index in scope.selectList) {
					str += "dictTypeIn=" + scope.selectList[index].dictType + "&";
				}
			}
			str = str.slice(0, -1);
			return str;
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "dictName", label: proxy?.$t("dict.tablist_label.dictname") },
			{ prop: "status", label: proxy?.$t("dict.tablist_label.status"), width: 100 },
			{ prop: "operation", label: proxy?.$t("dict.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const detailDialog = reactive({ visible: false, title: proxy?.$t("dict.dialog_title.add") });

		const currentDictType = ref({});
		const publicStore = PublicStore();
		return () => {
			return (
				<div>
					<UploadFile
						style="display: none;"
						ref={uploadFileDataEl}
						api={importDictData}
						headers={{ Authentication: publicStore.token }}
						params={{ systemId: state.systemId }}
						onSubmit={() => loadList}
					/>
					<UploadFile
						style="display: none;"
						ref={uploadFileEl}
						api={importDictType}
						headers={{ Authentication: publicStore.token }}
						params={{ systemId: state.systemId }}
						onSubmit={() => loadList}
					/>
					<TypeDialog
						width="600"
						v-model:visible={detailDialog.visible}
						title={detailDialog.title}
						detail={currentItem.value}
						onSubmit={() => {
							detailDialog.visible = false;
							proTableRef.value.getTableList();
						}}
					></TypeDialog>

					{SYSTEM_ID == "sansan" ? (
						<div class="flex">
							<div class="w-11/12">
								<el-tabs v-model={state.systemId} class="bg-white pl-6 pt-2" onTabChange={loadList}>
									{state.appletList.map((item: any) => {
										return (
											<el-tab-pane
												key={item.menuSystemId || item.id}
												label={item.name}
												name={item.menuSystemId || item.id}
											></el-tab-pane>
										);
									})}
								</el-tabs>
							</div>
							<el-popover placement="bottom" width="400" trigger="click">
								{{
									reference() {
										return (
											<el-link underline={false} class="flex-1 bg-white">
												{proxy?.$t("common.btn.search")}
											</el-link>
										);
									},
									default() {
										return (
											<el-input v-model={appName.value} placeholder={proxy?.$t("applet_dialog.placeholder.name")}>
												{{
													append() {
														return <el-button class="plus-icon iconfont iconsearch" onClick={getAppletList} />;
													}
												}}
											</el-input>
										);
									}
								}}
							</el-popover>
						</div>
					) : (
						""
					)}

					<div class="flex">
						<div class="w-2/5">
							<ProTable
								ref={proTableRef}
								title={btnList.value.length ? "" : proxy?.$t("dict.tab_title.dicttype")}
								columns={columns}
								requestApi={getTableList}
								dataCallback={dataCallback}
								initParam={state.searchParam}
								toolButton={false}
								custSearch
								onClickRow={(val: any) => (currentDictType.value = val)}
							>
								{{
									headerRightExt: () => {
										return (
											<div class="flex" style="height: 32px;">
												<el-input
													v-model={initParam.dictName}
													style="width:200px"
													placeholder={proxy?.$t("dict.input.placeholder")}
												/>
												<el-button onClick={() => proTableRef.value.getTableList()}>{proxy?.$t("dict.btn.query")}</el-button>
											</div>
										);
									},
									tableHeader: (scope: any) => {
										return (
											<div class="flex">
												{btnList.value?.map((item: any) => {
													return (
														<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
															<i class={`iconfont ${item.icon}`}></i>
															{item.menuName}
														</el-button>
													);
												})}
												<el-dropdown
													v-slots={{
														dropdown: () => {
															return (
																<el-dropdown-menu>
																	{batchList.value.map((item: any) => {
																		return (
																			<el-dropdown-item onClick={() => clickBtn(item.path, scope)}>
																				{item.menuName}
																			</el-dropdown-item>
																		);
																	})}
																</el-dropdown-menu>
															);
														}
													}}
												>
													<el-button type="primary" link>
														{proxy?.$t("dict.btn.dropdown")}
														<i class="el-icon--right iconfont iconchevron-down"></i>
													</el-button>
												</el-dropdown>
											</div>
										);
									},
									dictName: (scope: any) => {
										return (
											<el-link type="primary" onClick={() => clickBtn("mod", scope.row)}>
												{scope.row.dictName}
											</el-link>
										);
									},
									status: (scope: any) => {
										return (
											<OnlineStatus
												v-model={scope.row.status}
												onlineLabel={proxy?.$t("dict.status.online")}
												offlineLabel={proxy?.$t("dict.status.offline")}
											/>
										);
									},
									operation: (scope: any) => {
										return (
											<>
												<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("mod", scope.row)}>
													{proxy?.$t("dict.link.detail")}
												</el-link>
											</>
										);
									}
								}}
							</ProTable>
						</div>
						<div class="flex-1 pl-4">
							<DictDataList dictType={currentDictType.value} systemId={state.systemId}></DictDataList>
						</div>
					</div>
				</div>
			);
		};
	}
});
